package com.bruce.practice.thread;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.stream.IntStream;

/**
 * @author luotuan
 * @Description
 * @create 2020-05-19 10:48
 **/
public class CyclicBarrierTest {
    private static final int COUNT = 4;
    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(COUNT, new Runnable() {
            @Override
            public void run() {
                System.out.println("裁判发号施令");
            }
        });
        IntStream.range(0,COUNT).forEach((i)->{
            new Runner(String.valueOf(i),cyclicBarrier).start();
        });
    }
}
class Runner extends Thread{
    private String name;
    private CyclicBarrier cyclicBarrier;
    public Runner (String name,CyclicBarrier cyclicBarrier){
        this.name = name;
        this.cyclicBarrier = cyclicBarrier;
    }

    @Override
    public void run() {
        System.out.println("选手"+name+"开始准备");
        try {
            Thread.sleep(500L);
            System.out.println("选手"+name+"准备就绪");
            cyclicBarrier.await();
        } catch (InterruptedException | BrokenBarrierException e) {
            e.printStackTrace();
        }
        System.out.println("选手"+name+"开始跑步。。。。。。。。。");
    }
}
